<?php
namespace app\libs;

class RichContent {
    public function protocolToHtml($str) {
        // [video src="xxx" poster="xxx"]
        $str = preg_replace(
            '/\[video src="([^"]+)" poster="([^"]+)"\]/i',
            '<video src="${1}" poster="${2}" controls="controls"></video>',
            $str
        );

        // [img src="xxx"]
        $str = preg_replace('/\[img src="([^"]+)"\]/i', '<img src="${1}"/>', $str);

        // [link href="xxx"]xxx[/link]
        $str = preg_replace(
            '/\[link href="([^"]+)"\](.*)\[\/link\]/iU',
            '<a href="${1}" target="_blank">${2}</a>',
            $str
        );

        // [mark data-id="1"]xxx[/mark]
        $str = preg_replace_callback(
            '/\[mark\s*(?:data\-id="([^"]+)")?\](.*)\[\/mark\]/iU',
            function($m) {
                return $m[1] ? '<mark data-id="'. $m[1] .'">'. $m[2] .'</mark>' : "<mark>{$m[2]}</mark>";
            },
            $str
        );

        // [p data-role="xxx"]xxx[/p]
        $str = preg_replace_callback(
            '/\[p\s*(?:data\-role="([^"]+)")?\](.*)\[\/p\]/iU',
            function($m) {
                $con = $m[2] ? $m[2] : '<br />';

                return $m[1] ? '<p data-role="'. $m[1] .'">'. $con .'</p>' : "<p>{$con}</p>";
            },
            $str
        );

        // [b]xxx[/b]
        $str = str_ireplace([ '[b]', '[/b]' ], [ '<b>', '</b>' ], $str);
        $str = str_ireplace([ '[strong]', '[/strong]' ], [ '<strong>', '</strong>' ], $str);

        // [blockquote]xxx[/blockquote]
        $str = str_ireplace([ '[blockquote]', '[/blockquote]' ], [ '<blockquote>', '</blockquote>' ], $str);

        return $str;
    }
}
